package czx.service.impl;

import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import czx.model.Tuser;
import czx.model.ValidateException;
import czx.pageModel.User;
import czx.service.UserServiceI;
import czx.util.Encrypt;
import czx.util.HqlExp;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<Tuser> implements UserServiceI {

	private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Override
	public boolean ExistsName(Tuser t) {
		HqlExp hq = new HqlExp();
		hq.setCountHql("select count(*) from Tuser t where t.chname = :name and t.id != :id");
		hq.AddParam("name", t.getChname());
		hq.AddParam("id", t.getId());

		return count(hq) > 0;
	}

	@Override
	public void add(String name, String pwd) throws ValidateException {
		Tuser t = new Tuser();
		t.setChname(name);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		t.setPassword(Encrypt.e(pwd + sdf.format(t.getCreatedatetime())));
		if (ExistsName(t)) {
			throw new ValidateException(name + " 已经存在！");
		}
		t.Validate();
		save(t);
	}

	@Override
	public User login(User u) {
		HqlExp hqlExp = new HqlExp("from Tuser t where t.chname = :name and t.password = :pwd");
		logger.info(hqlExp.getHql());
		hqlExp.AddParam("name", u.getName());
		hqlExp.AddParam("pwd", Encrypt.e(u.getPwd()));
		Tuser user = get(hqlExp);
		if (user != null) {
			return u;
		}
		return null;
	}

	@Override
	public void test() {
		logger.info("成功进入Service");

	}

}
